package com.lrd.snapshotorder.config.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
import com.lrd.snapshotorder.config.datasource.shardingalgorithm.MultipleKeysShardingDatabase;
import com.lrd.snapshotorder.config.datasource.shardingalgorithm.MultipleKeysShardingTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.lrd.snapshotorder.mapper", sqlSessionTemplateRef = "shardingSqlSessionTemplate")
@Slf4j
public class ShardingDataSourceConfig {

    @Autowired
    private Environment environment;

    /**
     * 配置数据源0
     *
     * @return
     */
    @Bean(name = "ds_0")
    @Qualifier("ds_0")
    @ConfigurationProperties(prefix = "spring.ds0")
    public DataSource dataSource0() {
        return DruidDataSourceBuilder.create().build(environment, "spring.ds0");
    }

    /**
     * 配置数据源1
     *
     * @return
     */
    @Bean(name = "ds_1")
    @Qualifier("ds_1")
    @ConfigurationProperties(prefix = "spring.ds1")
    public DataSource dataSource1() {
        return DruidDataSourceBuilder.create().build(environment, "spring.ds1");
    }


    @Bean("shardingDataSource")
    //@Qualifier("shardingDataSource")
    public DataSource shardingDatasource() throws SQLException {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("ds_0", dataSource0());
        dataSourceMap.put("ds_1", dataSource1());
        //默认数据源
        DataSourceRule dataSourceRule = new DataSourceRule(dataSourceMap, "ds_0");
        //初始化表
        Map<String, List<String>> tableMap = initTableMap();
        if (tableMap.isEmpty()) {
            log.error("<===========初始化订单表失败,tablemap is null");
            return null;
        }
        //设置分库分表rule
        List<TableRule> tableRules = initTableRule(tableMap, dataSourceRule);
        if (tableRules.isEmpty()) {
            log.error("<===========初始化订单TABLE RULE,TABLERULES IS NULL");
            return null;
        }
        ShardingRule shardingRule = ShardingRule.builder()
                .dataSourceRule(dataSourceRule).tableRules(tableRules)
                .build();
        Properties props = new Properties();
        props.setProperty("check.table.metadata.enabled", "false");
        props.setProperty("sql.show", "true");
        return ShardingDataSourceFactory.createDataSource(shardingRule, props);
    }

    /**
     * 分库分表策略
     *
     * @param tableMap
     * @param dataSourceRule
     * @return
     */
    private List<TableRule> initTableRule(Map<String, List<String>> tableMap, DataSourceRule dataSourceRule) {
        List<TableRule> tableRuleList = Collections.synchronizedList(new ArrayList<>());
        TableRule tableRule = TableRule.builder("snapshot_order")
                .actualTables(tableMap.get("snapshotOrder"))
                .tableShardingStrategy(new TableShardingStrategy(Arrays.asList("id", "order_no", "batch_number"), new MultipleKeysShardingTable()))
                .databaseShardingStrategy(new DatabaseShardingStrategy(Arrays.asList("id", "order_no", "batch_number"), new MultipleKeysShardingDatabase()))
                .dataSourceRule(dataSourceRule)
                .build();
        tableRuleList.add(tableRule);
        return tableRuleList;
    }

    private Map<String, List<String>> initTableMap() {
        Map<String, List<String>> map = Collections.synchronizedMap(new HashMap<>(6));
        ArrayList<String> snapshotOrders = new ArrayList<String>();
        for (int i = 0; i < 32; i++) {
            snapshotOrders.add("snapshot_order_" + String.format("%02d", i));
        }
        map.put("snapshotOrder", snapshotOrders);
        return map;
    }

    /**
     * 需要手动配置事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier("shardingDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean(name = "shardingSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("shardingDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactory = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactory.setDataSource(dataSource);
        mybatisSqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));
        // MybatisConfiguration 配置
        //mybatisSqlSessionFactory.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis/mybatis-config.xml"));
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisSqlSessionFactory.setConfiguration(mybatisConfiguration);
        //开启分页插件
        PaginationInterceptor pageInterceptor = new PaginationInterceptor();
        mybatisSqlSessionFactory.setPlugins(pageInterceptor);
        return mybatisSqlSessionFactory.getObject();
    }

    @Bean(name = "shardingSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate shardingSqlSessionTemplate(@Qualifier("shardingSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
